package com.example.grade;

import java.util.*;

public class GradeManager {
    private final Map<String, Student>  students  = new HashMap<>();
    private final Map<String, Course>   courses   = new HashMap<>();
    // 用 (studentId,courseCode) 做 key，保证唯一
    private final Map<String, Grade>    grades    = new HashMap<>();

    /* ---------- 基础增删查 ---------- */
    public void addStudent(Student s) {
        students.put(s.getId(), s);
    }
    public void addCourse(Course c) {
        courses.put(c.getCode(), c);
    }
    public void addGrade(Grade g) {
        String key = g.getStudent().getId() + "_" + g.getCourse().getCode();
        grades.put(key, g);
    }

    public Student getStudent(String id) { return students.get(id); }
    public Course  getCourse(String code){ return courses.get(code); }

    /* 查询某学生某门课成绩 */
    public Grade queryGrade(String studentId, String courseCode) {
        String key = studentId + "_" + courseCode;
        return grades.get(key);
    }

    /* 计算某学生 GPA */
    public double calcGPA(String studentId) {
        double totalPoint = 0; // 加权绩点和
        double totalCredit = 0;
        for (Grade g : grades.values()) {
            if (g.getStudent().getId().equals(studentId)) {
                double credit = g.getCourse().getCredit();
                totalPoint += g.toPoint() * credit;
                totalCredit += credit;
            }
        }
        if (totalCredit == 0) return 0;
        return totalPoint / totalCredit;
    }

    /* 打印学生成绩单 */
    public void printTranscript(String studentId) {
        Student stu = students.get(studentId);
        if (stu == null) {
            System.out.println("学号不存在");
            return;
        }
        System.out.println("======== 成绩单 ========");
        System.out.println("学号：" + stu.getId() + "  姓名：" + stu.getName() + "  班级：" + stu.getClazz());
        grades.values().stream()
              .filter(g -> g.getStudent().getId().equals(studentId))
              .sorted(Comparator.comparing(g -> g.getCourse().getCode()))
              .forEach(g -> System.out.printf("%-10s%-15s%6.1f  %4.1f%n",
                      g.getCourse().getCode(),
                      g.getCourse().getName(),
                      g.getScore(),
                      g.toPoint()));
        System.out.printf("当前 GPA: %.2f%n", calcGPA(studentId));
    }
}